//
//  MachineSelectViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/16.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "SNJMachineSelectViewController.h"
#import "MachineSelectTableViewCell.h"
#import "GuidData.h"
#import "ProjectData.h"
#import "ProjectManager.h"
#import "MachineSelectData.h"
#import "SystemConfigTableViewCell.h"

#define SECTION_HEIGHT 50

@interface SNJMachineSelectViewController () {
    int mNumber;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,strong) NSIndexPath *oldIndexPath;
@property (nonatomic,strong) NSMutableArray *xlData;


@end

@implementation SNJMachineSelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    [self loadData];
    
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self loadSelectedProductSeries:self.tag];
}

/**
 *  初始化数据
 */
- (void)initData {
    self.dataSource = [NSMutableArray new];
    self.xlData = [NSMutableArray new];
}


#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"选择机型";
    
    //自定义完成选择按钮
    UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc] initWithTitle:@"完成选择" style:UIBarButtonItemStyleDone target:self action:@selector(onSave)];
    self.navigationItem.rightBarButtonItem = saveBtn;
    
    //自定义返回按钮
    UIBarButtonItem *returnBtn = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(onReturn)];
    self.navigationItem.leftBarButtonItem = returnBtn;
    
    //列表
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStylePlain];
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

#pragma mark - 事件响应
- (void)onSave {
    if (self.selectedData.count == 0) {
        kTipAlert(@"您还没有选择设备！");
        return;
    }
    if (self.machineSelectedBlock != nil) {
        self.machineSelectedBlock(self.selectedData);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onReturn {
    if (self.selectedData.count == 0) {
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"您还没有选择设备" cancelButtonTitle:@"继续选择" otherButtonTitles:[NSArray arrayWithObjects:@"不选了", nil] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                return;
            }
            else {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
        return;
    }
    if (self.machineSelectedBlock != nil) {
        self.machineSelectedBlock(self.selectedData);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 加载设备数据
/**
 *  加载所有数据
 */
- (void)loadData{
    
}

/**
 *  获取项目中选择了的室内机系列
 *
 *  @param tag <#tag description#>
 */
- (void)loadSelectedProductSeries:(NSString *)tag{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:tag forKey:@"tag"];
    [param setValue:[[ProjectManager manager] projectId] forKey:@"pid"]; //project ID
    
    [HttpClient getWithUrl:HTTP_GET_PROJECT_PRODUCT_SERIES token:[[AccountManager manager]token] paramDic:param resultClass:[GuidData class] success:^(GuidData *obj) {
        if (obj.getCandidateXlsResult != nil && obj.getCandidateXlsResult.count > 0) {
            for (GuidData *item in obj.getCandidateXlsResult) {
                [self.xlData addObject:item];
                //获取系列下得型式数据
                [self loadProductSeriesXs:item.guidId];
            }
        }
        CMLog(@"%@", obj);
    } failure:^(NSError *error) {
        CMLog(@"%@", error);
    }];
}

/**
 *  通过系列获取室内机系列下的型式列表
 *
 *  @param series 系列
 *  @param data   系列数据
 */
- (void)loadProductSeriesXs:(NSString *)series{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:self.tag forKey:@"tag"];
    [param setValue:series forKey:@"xl"]; //系列
    [param setValue:[NSNumber numberWithInt:1] forKey:@"ac"]; //0 仅包括未上市  1 仅包括已上市 2 已上市未上市都包括
    
    [HttpClient getWithUrl:HTTP_GET_PROJECT_PRODUCT_XS_BY_XL token:[[AccountManager manager]token] paramDic:param resultClass:[GuidData class] success:^(GuidData *obj) {
        
        if (obj.getProductXssResult != nil && obj.getProductXssResult.count > 0) {
            for (GuidData *item in obj.getProductXssResult) {
                MachineSelectData *xsData = [MachineSelectData new];
                xsData.xsObject = item;
                [self.dataSource addObject:xsData];
                //获取型式下的型号数据
                [self loadProductsBYXs:item.guidId inData:xsData];
            }
        }
        CMLog(@"%@", obj);
    } failure:^(NSError *error) {
        CMLog(@"%@", error);
    }];
}

/**
 *  通过型式获得产品型号
 *
 *  @param xs   型式
 *  @param data 型式数据
 */
- (void)loadProductsBYXs:(NSString *)xs inData:(MachineSelectData*)xsData{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:self.tag forKey:@"tag"];
    [param setValue:xs forKey:@"xs"]; //型式
    [param setValue:[NSNumber numberWithInt:[[ProjectManager manager] project].dfrType] forKey:@"dfr"];
    [param setValue:[NSNumber numberWithInt:1] forKey:@"ac"]; //0 仅包括未上市  1 仅包括已上市 2 已上市未上市都包括
    [param setValue:[NSNumber numberWithInt:0] forKey:@"si"];
    [param setValue:[NSNumber numberWithInt:-1] forKey:@"ei"];
    
    [HttpClient getWithUrl:HTTP_GET_PROJECT_PRODUCT_BY_XS token:[[AccountManager manager]token] paramDic:param resultClass:[GuidData class] success:^(GuidData *obj) {
        
        if (obj.getProductsByXsResult != nil && obj.getProductsByXsResult.count > 0) {
            if (xsData.xhData == nil) {
                xsData.xhData = [NSMutableArray new];
            }
            else {
                [xsData.xhData removeAllObjects];
            }
            
            //[xsData.xhData addObjectsFromArray:obj.getProductsByXsResult];
            
            for (GuidData *item in obj.getProductsByXsResult) {
                //判断是否有设备已经在选择的数据里
                BOOL hasSelected = NO;
                GuidData *hasSelectedItem = nil;
                for (GuidData *selected in self.selectedData) {
                    if ([selected.guidId isEqualToString:item.guidId]) {
                        hasSelected = YES;
                        hasSelectedItem = selected;
                        hasSelectedItem.isSelected = YES;
                        break;
                    }
                }
                if (hasSelected) {
                    [xsData.xhData addObject:hasSelectedItem];
                }
                else {
                    [xsData.xhData addObject:item];
                }
                
            }
            
            
            [self.tableView reloadData];
        }
        CMLog(@"%@", obj);
    } failure:^(NSError *error) {
        CMLog(@"%@", error);
    }];
}



#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    MachineSelectData *xsData = [self.dataSource objectAtIndex:section];
    if (xsData.xsOpened) {
        return xsData.xhData.count + 1;
    }
    else {
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MachineSelectData *xsData = [self.dataSource objectAtIndex:indexPath.section];
    if (indexPath.row == 0) {
        //当前是要显示型式数据
        static NSString *identifier1 = @"XSCell";
        SystemConfigTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier1];
        if (cell == nil) {
            cell = [[SystemConfigTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier1];
            
        }
        [cell setInfoLabelHidden:YES];
        [cell setTitleStr:xsData.xsObject.name];
        [cell setSubContentClosed:!xsData.xsOpened];
        return cell;
    }
    else {
        static NSString *identifier = @"MachineSelectCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.textLabel.textColor = CM_TABLE_TITLE_COLOR;
        cell.textLabel.font = [UIFont systemFontOfSize:kListTitleFontSize];
        GuidData *item = [xsData.xhData objectAtIndex:indexPath.row - 1];
        cell.textLabel.text = item.name;
        if (item.isSelected) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        return cell;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MachineSelectData *xsData = [self.dataSource objectAtIndex:indexPath.section];
    if (indexPath.row == 0) {
        xsData.xsOpened = !xsData.xsOpened;
        NSIndexSet *section = [NSIndexSet indexSetWithIndex:indexPath.section];
        [self.tableView reloadSections:section withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    else {
        //保存型式数据，用来做自动选型
        // 选择cell
        GuidData *item = [xsData.xhData objectAtIndex:indexPath.row - 1];
        if (item.count == 0) {
            item.count = 1; //默认是先选择一台
        }
        if (self.selectedData == nil) {
            self.selectedData = [NSMutableArray new];
        }
        if (self.couldMultipleSelect) {
            //多选
            item.isSelected = !item.isSelected;
            
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
            if (item.isSelected) {
                [self.selectedData addObject:item];
            }
            else {
                [self.selectedData removeObject:item];
            }
            
            //给出提示
            NSMutableString *selectStr = [NSMutableString new];
            if (self.selectedData.count > 0) {
                [selectStr appendString:@"您已经选择了："];
                for (GuidData *selected in self.selectedData) {
                    [selectStr appendString:selected.name];
                    [selectStr appendString:@" "];
                }
            }
            else {
                [selectStr appendString:@"您当前没有选择设备"];
            }
            [Tools showMessageCenter:selectStr];
        }
        else {
            [self.selectedData removeAllObjects];
            [self.selectedData addObject:item];
            if (self.machineSelectedBlock != nil) {
                self.machineSelectedBlock(self.selectedData);
            }
            [self.navigationController popViewControllerAnimated:YES];
//            if (self.oldIndexPath == nil) {
//                item.isSelected = !item.isSelected;
//                self.oldIndexPath = indexPath;
//                [self.selectedData addObject:item];
//                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
//            }
//            else if (self.oldIndexPath == indexPath){
//                item.isSelected = !item.isSelected;
//                if (item.isSelected) {
//                    [self.selectedData addObject:item];
//                }
//                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
//            }
//            else {
//                item.isSelected = YES;
//                [self.selectedData addObject:item];
//                MachineSelectData *oldXlData = [self.dataSource objectAtIndex:self.oldIndexPath.section];
//                GuidData *oldItem = [oldXlData.xhData objectAtIndex:self.oldIndexPath.row - 1];
//                oldItem.isSelected = NO;
//                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, self.oldIndexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
//                self.oldIndexPath = indexPath;
//            }
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        //当前是要显示系列数据
        static NSString *identifier1 = @"XSCell";
        SystemConfigTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier1];
        if (cell == nil) {
            cell = [[SystemConfigTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier1];
            
        }
        [cell setInfoLabelHidden:YES];
        return [cell getHeight];
    }
    else {
        static NSString *identifier = @"MachineSelectCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        return cell.height;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
